// permission.ts
import { RouteRecordRaw } from "vue-router";
import { defineStore } from "pinia";
import { constantRoutes } from "@/router";
import { store } from "@/store";
import { getRoutesApi } from "@/api/menu"
import router from '@/router'; // 添加导入

const modules = import.meta.glob("../../views/**/**.vue");
const Layout = () => import("@/layout/index.vue");

// 定义 key 常量用于 localStorage 存储
const ROUTES_STORAGE_KEY = 'X-app_persisted_raw_routes';

/**
 * 递归过滤有权限的异步(动态)路由
 */
const filterAsyncRoutes = (routes: RouteRecordRaw[]) => {
    const asyncRoutes: RouteRecordRaw[] = [];
    routes.forEach((route) => {
        const tmpRoute = { ...route };
        if (!route.name) {
            tmpRoute.name = route.path;
        }
        if (tmpRoute.component?.toString() == "Layout") {
            tmpRoute.component = Layout;
        } else if (tmpRoute.component) {
            const component = modules[`../../views/${tmpRoute.component}.vue`];
            tmpRoute.component = component || (() => import('@/views/error/404.vue'));
        }
        if (tmpRoute.children) {
            tmpRoute.children = filterAsyncRoutes(tmpRoute.children);
        }
        asyncRoutes.push(tmpRoute);
    });
    return asyncRoutes;
};

// 添加函数：将动态路由添加到路由实例
const addRoutesToRouter = (routes: RouteRecordRaw[]) => {
    routes.forEach(route => {
        // 检查是否已存在相同路径的路由
        if (!router.hasRoute(route.name as string)) {
            router.addRoute(route);
        }
    });
    
    // 确保404路由在最后
    if (!router.hasRoute('404')) {
        router.addRoute({
            path: '/:pathMatch(.*)*',
            redirect: '/404',
        });
    }
};

export const usePermissionStore = defineStore("permission", () => {
    const storedRawRoutes = localStorage.getItem(ROUTES_STORAGE_KEY);
    const initialRoutes = storedRawRoutes ? filterAsyncRoutes(JSON.parse(storedRawRoutes)) : [];
    
    // 初始化时添加动态路由到路由实例
    if (initialRoutes.length > 0) {
        addRoutesToRouter(initialRoutes);
    }

    const routes = ref<any[]>(constantRoutes.concat(initialRoutes));

    function setRoutes(newRoutes: any[]) {
        localStorage.setItem(ROUTES_STORAGE_KEY, JSON.stringify(newRoutes));
        const accessedRoutes = filterAsyncRoutes(newRoutes);
        routes.value = constantRoutes.concat(accessedRoutes);
        
        // 添加新路由到路由实例
        addRoutesToRouter(accessedRoutes);
    }

    function generateRoutes() {
        return new Promise<RouteRecordRaw[]>((resolve, reject) => {
            getRoutesApi()
                .then((data: any) => {
                    setRoutes(data.data);
                    resolve(filterAsyncRoutes(data.data));
                })
                .catch((error) => {
                    reject(error);
                });
        });
    }

    /**
     * 混合模式左侧菜单
     */
    const mixLeftMenu = ref<RouteRecordRaw[]>([]);
    function getMixLeftMenu(activeTop: string) {
        routes.value.forEach((item) => {
            if (item.path === activeTop) {
                mixLeftMenu.value = item.children || [];
            }
        });
    }

    return { routes, setRoutes, generateRoutes, getMixLeftMenu, mixLeftMenu };
});

export function usePermissionStoreHook() {
    return usePermissionStore(store);
}